package com.java.service.impl;

import java.util.Collection;
import java.util.List;

import com.java.model.Student;
import com.java.myJdbcutils.JdbcUtils;
import com.java.service.StudentService;
import com.java.vo.Result;

/**
 * 使用数据库实现
 */
public class StudentServiceDbImpl implements StudentService {
	
	/**
	 * 新增一个学生
	 */
	public Result add(int id, String name, int age, double score) {
		Student student = new Student();
		student.setId(id);
		student.setAge(age);
		student.setName(name);
		student.setScore(score);
		return add(student);
	}
	
	/**
	 * 新增学生
	 */
	public Result add(Student student) {
		Result result = new Result();
		
		String sql = "insert into student_score values(?,?,?,?)";
		int i = JdbcUtils.execute(sql, new Object[]{
			student.getId(),
			student.getName(),
			student.getAge(),
			student.getScore()
		});
		if(i==0) {
			return result.fail("新增学员失败");
		}
		return result.success("恭喜您，新增学员成功");
	}
	
	/**
	 * 修改指定学号学生的姓名
	 */
	public Result edit(int id, String name) {
		Student student = new Student();
		student.setId(id);
		student.setName(name);
		return edit(student);
	}
	
	/**
	 * 修改指定学号学生的成绩
	 */
	public Result edit(int id, double score) {
		Student student = new Student();
		student.setId(id);
		student.setScore(score);
		return edit(student);
	}
	
	/**
	 * 修改指定学号学生的所有信息
	 */
	public Result edit(Student student) {
		Result result = new Result();
		Student stu = find(student.getId());
		if (stu == null) {
			return result.fail("该学生不存在，不能进行编辑");
		} else {
			String sql = "update student_score set ";
			if (student.getAge() > 0) {
				sql += "age = " + student.getAge() + ",";
			}
			if (student.getName() != null && !"".equals(student.getName())) {
				sql += "sname = '" + student.getName() + "',";
			}
			if (student.getScore() > 0) {
				sql += "score = '" + student.getScore() + "',";
			}
			sql = sql.substring(0, sql.length() - 1);
			sql += " where sid = ?";
			JdbcUtils.execute(sql, new Object[]{
				student.getId()
			});
		}
		return result.success("恭喜你，编辑学员成功");
	}
	
	/**
	 * 删除指定ID的学生
	 */
	public Result delete(int id) {
		Result result = new Result();
		String sql = "delete student_score where sid = ?";
		int i = JdbcUtils.execute(sql, new Object[]{id});
		if (i > 0) {
			return result.success("恭喜您，删除学员成功");
		} else {
			return result.fail("学员不存在");
		}
	}
	
	/**
	 * 查找指定ID的学生
	 * 
	 * @return Student | null
	 */
	public Student find(int id) {
		String sql = "select * from student_score where sid = ?";
		List<Student> students = JdbcUtils.query(sql, new Object[]{id}, Student.class);
		return students == null || students.isEmpty() ? null : students.get(0);
	}
	
	/**
	 * 打印所有学生信息
	 */
	public Collection<Student> listAll() {
		String sql = "select * from student_score";
		return JdbcUtils.query(sql, null, Student.class);
	}
	
	@Override
	public void save() {
		System.out.println("功能尚未实现");
	}
	
	@Override
	public void load() {
	}
	
}
